appCtrl = angular.module('xqkj.controllers', [])
  .controller('DashCtrl', function($scope, $state, UtilsService, UserService) {

  })
  .controller('DashHomeCtrl', function($scope, $rootScope, $ionicSlideBoxDelegate, $ionicScrollDelegate, $interval, $interval, $state, $document, $stateParams, UtilsService, ArepoService, ProductClassService) {
    $scope.getSubClassHeight = function(){
      return ((window.innerWidth - 40) / 4  + 52) * 2
    }
    $scope.getSaleHeight = function(){
      return 47 + (window.innerWidth - 50) / 3
    }
    $scope.getClass1Height = function(){
      return window.innerWidth / 2
    }
    // $scope.height1 = 800;
    // $scope.height1 = 4000;
    // var stop = $interval(function() {
    //   var box1 = document.getElementById('home-view');
    //   if(!box1){
    //     return;
    //   }
    //
    //   $interval.cancel(stop);
    //
    //   var prey = 0;
    //   var starty = 0;
    //   var dist = 0;
    //   var top = 0;
    //
    //   box1.addEventListener('touchstart', function(e) {
    //     var touchobj = e.changedTouches[0]; // reference first touch point (ie: first finger)
    //     starty = parseInt(touchobj.clientY); // get x position of touch point relative to left edge of browser
    //     prey = starty;
    //     // statusdiv.innerHTML = 'Status: touchstart<br> ClientX: ' + startx + 'px'
    //     // console.log('starty' + starty);
    //     e.preventDefault();
    //   }, false);
    //
    //   box1.addEventListener('touchmove', function(e) {
    //     var touchobj = e.changedTouches[0]; // reference first touch point for this event
    //     var dist = parseInt(touchobj.clientY) - prey;
    //     // statusdiv.innerHTML = 'Status: touchmove<br> Horizontal distance traveled: ' + dist + 'px'
    //     // console.log(dist);
    //     top -= dist;
    //     if(top < 0){
    //       top = 0
    //     }
    //
    //     $ionicScrollDelegate.scrollTo($ionicScrollDelegate.getScrollPosition().left, top);
    //     prey = parseInt(touchobj.clientY);
    //     e.preventDefault();
    //   }, false);
    //
    //   box1.addEventListener('touchend', function(e) {
    //     var touchobj = e.changedTouches[0]; // reference first touch point for this event
    //     // statusdiv.innerHTML = 'Status: touchend<br> Resting x coordinate: ' + touchobj.clientX + 'px'
    //     // console.log(touchobj);
    //     e.preventDefault();
    //   }, false);
    // }, 500);

    var stop = $interval(function() {
      var box1 = document.getElementById('home-view');
      if (!box1) {
        return;
      }

      $interval.cancel(stop);
      stroll.bind(box1);
    })

    if (!UtilsService.isDistExist()) {
      $state.go('district.list');
      $rootScope.$broadcast('loading:showMessage', {
        message: '请选择小区'
      });
      return;
    }
    $scope.dist = UtilsService.getDist();
    if ($scope.dist && $scope.dist.name.length > 4) {
      $scope.dist.name = $scope.dist.name.substring(0, 4) + '...';
    }
    // console.log($scope.dist);
    $scope.homepics = [];

    // console.log(UtilsService.getDist());

    $scope.refresh = function() {
      // console.log($rootScope.homepics);
      ArepoService.getHomePics({
        id: UtilsService.getAid()
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.homepics = response.data.homepics;
          $ionicSlideBoxDelegate.update()
            // console.log(angular.toJson($scope.homepics));
        }
      });

      $rootScope.$on('$stateChangeSuccess', function(e, toState, toParams, fromState, fromParams) {
        if (fromState.name === 'district' && toParams.updated == true) {
          Todo.getAll().success(function(data) {
            $scope.refresh()
          });
          $stateParams.updated = false;
        }
      })


      ArepoService.getHomeAds({
        id: UtilsService.getAid()
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.homeads = response.data.homeads;
        }
        $scope.$broadcast('scroll.refreshComplete');

      });

      ArepoService.getSales({
        id: UtilsService.getAid(),
        num: 3
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.homesales = response.data.products;
        }
      });

      // 获取分类
      ProductClassService.getFirst().$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.classes = response.data.classes;
        }
      });
    }

    if ($rootScope.dist) {
      $scope.refresh()
    }


    $scope.picClick = function(pic) {
      // 设置页面跳转url
      switch (pic.linktype) {
        case '1':
          $state.transitionTo('goods.detail', {
            id: pic.content
          }, {
            reload: true
          });
          // $scope.homepics[i].url = '#/goods/' + $scope.homepics[i].content;
          break;
        case '2':
          // 图片页面
          $state.transitionTo('img', {
            imgurl: server + pic.content
          }, {
            reload: true
          });
          // $scope.homepics[i].url = '#/img/' + server + $scope.homepics[i].content;
          break;
        case '3':
          $state.transitionTo('goods.class', {
            classid: pic.content
          }, {
            reload: true
          });
          // $scope.homepics[i].url = '#/goods/class/' + $scope.homepics[i].content;
          break;
        default:
      }
    }
    $scope.goSearch = function(classid, type) {
      $state.transitionTo('goods.search', {
        classid: classid ? classid : 0,
        type: type
      }, {
        reload: true
      });
    }


    $scope.goSaleDetail = function(id) {
      $state.transitionTo('goods.saledetail', {
        id: id
      }, {
        reload: true
      });
    }

    $scope.goClass = function(id, type) {
      $state.transitionTo('goods.class', {
        classid: id,
        type: type
      }, {
        reload: true
      });
    }

    $scope.selectLoc = function() {
      $state.transitionTo('district.list', {}, {
        reload: true
      });
    }
  })

.controller('DashClassCtrl', function($scope, $state, $rootScope, $document, $interval, $ionicScrollDelegate, UtilsService, ArepoService, ProductClassService) {
  // var stop = $interval(function() {
  //   var box1 = document.getElementById('class-view');
  //   if(!box1){
  //     return;
  //   }
  //
  //   $interval.cancel(stop);
  //   var prey = 0;
  //   var starty = 0;
  //   var dist = 0;
  //   var top = 0;
  //
  //   box1.addEventListener('touchstart', function(e) {
  //     var touchobj = e.changedTouches[0]; // reference first touch point (ie: first finger)
  //     starty = parseInt(touchobj.clientY); // get x position of touch point relative to left edge of browser
  //     prey = starty;
  //     // statusdiv.innerHTML = 'Status: touchstart<br> ClientX: ' + startx + 'px'
  //     console.log('starty' + starty);
  //     e.preventDefault();
  //   }, false);
  //
  //   box1.addEventListener('touchmove', function(e) {
  //     var touchobj = e.changedTouches[0]; // reference first touch point for this event
  //     var dist = parseInt(touchobj.clientY) - prey;
  //     // statusdiv.innerHTML = 'Status: touchmove<br> Horizontal distance traveled: ' + dist + 'px'
  //     console.log(dist);
  //     top -= dist;
  //     if(top < 0){
  //       top = 0
  //     }
  //     $ionicScrollDelegate.scrollTo($ionicScrollDelegate.getScrollPosition().left, top);
  //     prey = parseInt(touchobj.clientY);
  //     e.preventDefault();
  //   }, false);
  //
  //   box1.addEventListener('touchend', function(e) {
  //     var touchobj = e.changedTouches[0]; // reference first touch point for this event
  //     // statusdiv.innerHTML = 'Status: touchend<br> Resting x coordinate: ' + touchobj.clientX + 'px'
  //     // console.log(touchobj);
  //     e.preventDefault();
  //   }, false);
  // }, 500);

  // 用于两个页面交互
  $scope.selectedC1 = 0;
  $scope.c1 = [];
  $scope.c2 = [];
  $scope.dist = UtilsService.getDist();

  // 获取商品一级列表
  ProductClassService.getFirst().$promise.then(function(response) {
    if (UtilsService.isResponseOk(response)) {
      $scope.c1 = response.data.classes;
      if ($scope.c1.length > 0) {
        // 获取第一个的二三级列表，其中包括了第三级
        ProductClassService.get({
          type: 2,
          parent_id: $scope.c1[0].product_class_id
        }).$promise.then(function(response) {
          if (UtilsService.isResponseOk(response)) {
            $scope.c2 = response.data.classes;
            $scope.curClass = $scope.c1[0];

            // 三个一组分开
            for (var id = 0; id < $scope.c2.length; id++) {
              var temp = [];
              $scope.c2[id].class = [];
              for (var i = 0; i < $scope.c2[id].sub_class.length; i++) {
                var realid = parseInt(i / 3);

                if (i % 3 == 0) {
                  $scope.c2[id].class[realid] = [];
                }
                // console.log(realid);
                $scope.c2[id].class[realid].push($scope.c2[id].sub_class[i]);
              }
            }
          }
        });
      }
    }
  });


  $scope.changeClass = function(class1) {
    if (class1 == $scope.curClass) {
      return;
    }

    $scope.curClass = class1;
    ProductClassService.get({
      type: 2,
      parent_id: $scope.curClass.product_class_id
    }).$promise.then(function(response) {
      if (UtilsService.isResponseOk(response)) {
        $scope.c2 = response.data.classes;
        // 三个一组分开
        for (var id = 0; id < $scope.c2.length; id++) {
          $scope.c2[id].class = [];
          for (var i = 0; i < $scope.c2[id].sub_class.length; i++) {
            var realid = parseInt(i / 3);

            if (i % 3 == 0) {
              $scope.c2[id].class[realid] = [];
            }
            $scope.c2[id].class[realid].push($scope.c2[id].sub_class[i]);
          }
        }

        $ionicScrollDelegate.resize()
        $ionicScrollDelegate.scrollTo($ionicScrollDelegate.getScrollPosition().left, 0);

      }
    });
  }

  $scope.goSearch = function() {
    $state.transitionTo('goods.search', {
      classid: -1,
      type: 1
    }, {
      reload: true
    });
  }
})

.controller('DashFormCtrl', function($scope, $stateParams) {})

.controller('DashCartCtrl', function($scope, $rootScope, $state, UtilsService, UserService) {
    $scope.edit = false;

    // 选中商品
    $scope.goodschecked = [];
    $scope.checkAll = true;

    // 设置购物车内物品数量
    $scope.setNum = function(goods, num) {
      if (goods.xg_amount && parseInt(goods.xg_amount) < parseInt(goods.num) + num) {
        // 限购返回
        return;
      }
      if ($scope.edit) {
        return;
      }
      var curnum = parseInt(goods.num) + parseInt(num);
      if (curnum <= 0) {
        if (!confirm('是否删除该商品')) {
          return;
        }
      }
      UserService.changeNumOfGoodsInCart({
        shopping_cart_id: goods.shopping_cart_id,
        num: curnum
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {

          if (curnum <= 0) {
            var key = goods.class3 + '_' + goods.sendtype;
            var i = $scope.cartproducts[key]['products'].indexOf(goods);
            var index = $scope.goodschecked.indexOf(goods);
            if (index >= 0) {
              $scope.goodschecked.splice(index, 1);
            }
            $scope.cartproducts[key]['products'].splice(i, 1);

            if ($scope.cartproducts[key]['products'].length == 0) {
              delete $scope.cartproducts[key];

              // var j = $scope.cartproducts.indexOf($scope.cartproducts[key]);
              //
              // $scope.cartproducts.splice(j, 1);
            }
          } else {
            goods.num = curnum;
          }
        }
      })
    }


    $scope.calculateAmount = function() {
      var count = 0;
      for (var i in $scope.cartproducts) {
        for (var j in $scope.cartproducts[i]['products']) {
          if ($scope.cartproducts[i] == undefined) {
            continue;
          }
          var goods = $scope.cartproducts[i]['products'][j];
          // console.log(goods);

          if (goods.isCheck) {
            count += parseFloat(goods.num) * parseFloat(goods.cx_price || goods.kj_price);
          }
        }
      }

      return count.toFixed(1);
    }

    // 购物车全选中
    $scope.$watch('checkAll', function(newValue, oldValue) {
      if (newValue == oldValue) {
        return;
      }
      $scope.goodschecked = [];

      // 删除
      if (!newValue) {
        for (var i in $scope.cartproducts) {
          for (var j in $scope.cartproducts[i]['products']) {
            $scope.cartproducts[i]['products'][j].isCheck = false;
          }
        }
      } else {
        for (var i in $scope.cartproducts) {
          for (var j in $scope.cartproducts[i]['products']) {
            // 原来不在的，选中添加
            $scope.goodschecked.push($scope.cartproducts[i]['products'][j]);
            $scope.cartproducts[i]['products'][j].isCheck = true;
          }
        }
      }
    })

    $scope.toPay = function() {
      if ($scope.goodschecked.length <= 0) {
        $rootScope.$broadcast('loading:showMessage', {
          message: '您还没有选中商品'
        });
        return;
      }
      $rootScope.goodslist = $scope.goodschecked;
      $state.transitionTo('order.chooseloc', {}, {
        reload: true,
        inherit: false,
        notify: true
      });
    }

    // 选中goods
    $scope.setGoods = function(goods) {
      if (!$scope.edit) {
        goods.isCheck = !goods.isCheck;
        if (goods.isCheck) {
          $scope.goodschecked.push(goods);
        } else {
          var i = $scope.goodschecked.indexOf(goods);

          $scope.goodschecked.splice(i, 1);
        }
      }
    }


    // 设置 是否是编辑状态
    $scope.setEdit = function() {
      $scope.edit = !$scope.edit;
    }

    // 删除商品
    $scope.deleteGoods = function(goods) {
      UserService.deleteCart({
        value: goods.shopping_cart_id
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          // 从页面删除
          var key = goods.class3 + '_' + goods.sendtype;
          var i = $scope.cartproducts[key]['products'].indexOf(goods);
          $scope.cartproducts[key]['products'].splice(i, 1);
          //　删除类别
          if ($scope.cartproducts[key]['products'].length == 0) {
            // $scope.cartproducts.remove(key);
            delete $scope.cartproducts[key];
            // var j = $scope.cartproducts.indexOf($scope.cartproducts[key]);
            // $scope.cartproducts.splice(j, 1);
          }
        }
      })
    }

    // 设置运费
    $scope.getsendpirce = function() {
      var count = $scope.calculateAmount()
      if (count == 0) {
        return '0.0';
      }
      if (count < 9) {
        return '6.0';
      }
      var result = false; // 判断是否有满9包邮的
      for (var i in $scope.goodschecked) {
        var goods = $scope.goodschecked[i];
        if (goods.tag == '1') {
          result = true;
          break;
        }
      }

      return result ? '0.0' : '6.0';
    }


    if (UtilsService.isLogin()) {
      UserService.getCart().$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.cartproducts = response.data.result;
          $scope.activity = response.data.activity;

          // 设置限购
          for (var i in $scope.cartproducts) {
            for (var j in $scope.cartproducts[i]['products']) {
              $scope.cartproducts[i]['products'][j].isCheck = true;

              $scope.goodschecked.push($scope.cartproducts[i]['products'][j])
              var goods = $scope.cartproducts[i]['products'][j];
              if (goods.xg_amount && parseInt(goods.xg_amount) < goods.num) {
                goods.num = parseInt(goods.xg_amount);
              }
            }
          }
        }
      });
    }

  })
  .controller('DashMineCtrl', function($scope, $rootScope, UtilsService) {

    $scope.user = UtilsService.getUser();
  })
  .controller('ImgCtrl', function($scope, $rootScope, $stateParams, UtilsService) {
    $scope.imgurl = $stateParams.imgurl;
    console.log($scope.imgurl);
  });
